package com.xiangyueEducation.uploaderCloud.interceptor;

import com.xiangyueEducation.uploaderCloud.utils.JwtHelper;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;
@Component
public class MyHandShakeInterceptor implements HandshakeInterceptor {
    @Autowired
    JwtHelper jwtHelper;


    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        //验证两个参数是好友关系

        //如果验证通过，则将好友关系存储到attributes中
        if (request instanceof ServletServerHttpRequest){
            ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
            HttpServletRequest httpRequest = servletRequest.getServletRequest();
            String token = httpRequest.getParameter("t");
            Long userId = jwtHelper.getUserId(token);
            Long receiverId = Long.parseLong(httpRequest.getParameter("receiverId"));
            attributes.put("senderId",userId);
            attributes.put("receiverId",receiverId);
            return true;
        }
        return false;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {

    }
}
